//
//  SessionViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/17.
//  Copyright © 2017年 song ce. All rights reserved.


#import "SessionViewController.h"
#import "EaseMessageViewController.h"
#import "EaseConvertToCommonEmoticonsHelper.h"
#import "EaseLocalDefine.h"
#import "UILabel+ChangeLineSpaceAndWordSpace.h"
#import "CYLTabBarController.h"
#import "MMDrawerController.h"
@interface SessionViewController ()<UITableViewDelegate,UITableViewDataSource,EMChatManagerDelegate>
@property(nonatomic,strong)UITableView *tableV;
@property(nonatomic,strong)UIImageView *noDataIUmageV;
@property(nonatomic,strong)NSMutableArray *dataSource;//好友列表
@property(nonatomic,assign)BOOL  isIgnoreUnread;
@property(nonatomic,assign)BOOL  isdeleteSession;
@property(nonatomic,assign)NSInteger  currentSessionRow;

@end

@implementation SessionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSource = [NSMutableArray array];
    [self tableViewAndHeaderView];
    //聊天结束后刷新会话列表
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(needToRefreshSessionList) name:@"needToRefreshSessionList" object:nil];
    [AppDelegate appDealegate].isNeedToSetSixinBadge = YES;
    //删除会话
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deleteCurrentSession) name:@"deleteCurrentSession" object:nil];
    //如果已经登录则加载数据  如果为登录则添加通知通过登录后的通知加载数据
    if([AppDelegate appDealegate].uid.length){
        [self loadData];
        return;
    }
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadData) name:@"loginSuccess" object:nil];
}

-(void)deleteCurrentSession{
    self.isdeleteSession = YES;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

-(void)needToRefreshSessionList{
    if(self.isdeleteSession){
        self.isdeleteSession = NO;
        [self.dataSource removeObjectAtIndex:self.currentSessionRow];
        [self.tableV reloadData];
        return;
    }
    [self loadData];
}
-(void)loadData{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSArray* sorted = [conversations sortedArrayUsingComparator:
                       ^(EMConversation *obj1, EMConversation* obj2){
                           EMMessage *message1 = [obj1 latestMessage];
                           EMMessage *message2 = [obj2 latestMessage];
                           if(message1.timestamp > message2.timestamp) {
                               return(NSComparisonResult)NSOrderedAscending;
                           }else {
                               return(NSComparisonResult)NSOrderedDescending;
                           }
                       }];
    if(self.dataSource.count){
        [self.dataSource removeAllObjects];
    }
    if (sorted.count == 0) {
        self.tableV.hidden = YES;
        [self.view addSubview:self.noDataIUmageV];
    }else{
        [self.noDataIUmageV removeFromSuperview];
        NSInteger unreadCount = 0;
        for (EMConversation *converstion in sorted) {
            if(self.isIgnoreUnread){
                self.isIgnoreUnread = NO;
                [converstion markAllMessagesAsRead:nil];
            }
            unreadCount += converstion.unreadMessagesCount;
            EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:converstion];
            if (model.conversation.type == EMConversationTypeChat) {
                [self.dataSource addObject:model];
            }
        }
        [self setSiXinBadge:unreadCount];
        [self.tableV reloadData];
         self.tableV.hidden = NO;
    }
}

- (void)tableViewAndHeaderView{
    //表视图
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 2, Main_Screen_Width, Main_Screen_Height-49-kNaviBarHeight-44-2) style:UITableViewStylePlain];
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = [UIColor colorWithRed:242./255 green:242./255 blue:242./255 alpha:1.];
    _tableV.delegate = self;
    _tableV.dataSource =self;
    [self.view addSubview:_tableV];
      _tableV.tableFooterView = [[UIView alloc]init];
    _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableV.hidden = YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ident=@"sessioncell";
    SessionCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
        if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"SessionCell" owner:self options:nil]lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    EaseConversationModel *model = self.dataSource[indexPath.row];
    model.lastTime =[self latestMessageTimeForConversationModel:model];
    model.lastMessage =[self latestMessageTitleForConversationModel:model];
    cell.model = model;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 73;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.currentSessionRow = indexPath.row;
    EaseConversationModel *model = self.dataSource[indexPath.row];
    EaseMessageViewController *chatController = [[EaseMessageViewController alloc] initWithConversationChatter:model.conversation.conversationId conversationType:EMConversationTypeChat];
    chatController.vcName = model.userName;
    chatController.hidesBottomBarWhenPushed = YES;
    [[self secondNavigationController] pushViewController:chatController animated:YES];
    [self loadData];
}
- (BaseNavigationViewController*)secondNavigationController{
    UIResponder *next = self.nextResponder;
    while (next!=nil) {
        if([next isKindOfClass:[BaseNavigationViewController class]]){
            return (BaseNavigationViewController*)next;
        }
        next = next.nextResponder;
    }
    return nil;
}

 //获取会话最近一条消息时间
- (NSString *)latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTime = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        double timeInterval = lastMessage.timestamp;
        if(timeInterval > 140000000000) {
            timeInterval = timeInterval / 1000;
        }
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        latestMessageTime = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
    }
    return latestMessageTime;
}

- (NSString *)latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTitle = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];
    if (lastMessage) {
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSEaseLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSEaseLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSEaseLocalizedString(@"message.location1", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSEaseLocalizedString(@"message.video1", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSEaseLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
    }
    return latestMessageTitle;
}

//设置私信的未读总条数
-(void)setSiXinBadge:(NSInteger)unreadCount{
    [AppDelegate appDealegate].messageCount = unreadCount;
     [[NSNotificationCenter defaultCenter]postNotificationName:@"messageCount" object:@(unreadCount)];
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    MMDrawerController *mm =(MMDrawerController*)window.rootViewController;
    CYLTabBarController *tabBar = (CYLTabBarController*)mm.centerViewController;
    UIViewController *private =tabBar.viewControllers[2];
    if(unreadCount==0){
        private.tabBarItem.badgeValue = nil;
         [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        return;
    }
    private.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:unreadCount];
}

//忽略未读
-(void)ignoreAllUnreadSessionMessage{
    self.isIgnoreUnread = YES;
    [self loadData];
}

-(UIImageView *)noDataIUmageV{
    if(_noDataIUmageV==nil){
        _noDataIUmageV = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_zanwushuju"]];
        _noDataIUmageV.frame = CGRectMake((Main_Screen_Width-100)/2, (self.view.size.height-115-49-44-kNaviBarHeight)/2, 100, 115);
    }
    return _noDataIUmageV;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
